﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;

namespace Twi.COMMON.HTTP
{
    public class ServerAddress
    {
        private static string filePath = "ServerAddress.xml";
        //private static string cookiesRootName = "Cookies";

        public static List<XElement> GetServerAddress()
        {
            List<XElement> serverAddressList = new List<XElement>();
            if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + filePath))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(System.AppDomain.CurrentDomain.BaseDirectory + filePath);
                XElement xe = XElement.Parse(xmlDoc.InnerXml);
                if (xe != null && xe.HasElements)
                    serverAddressList = xe.Elements().ToList();
            }
            else if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "Client/" + filePath))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(System.AppDomain.CurrentDomain.BaseDirectory + "Client/" + filePath);
                XElement xe = XElement.Parse(xmlDoc.InnerXml);
                if (xe != null && xe.HasElements)
                    serverAddressList = xe.Elements().ToList();
            }
            return serverAddressList;
        }

        public static XElement GetServerAddressRoot()
        {
            if (File.Exists(getConfigFilePath()))
            {
                return XElement.Load(System.AppDomain.CurrentDomain.BaseDirectory + filePath);
            }
            return new XElement("ServerAddresses");
        }

        private static string getConfigFilePath()
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\Settings.config";
            if (!File.Exists(filePath))
            {
                filePath = AppDomain.CurrentDomain.BaseDirectory + "\\..\\Settings.config";
            }
            return filePath;
        }
    }
}
